package com.longcai.cm.api.api4order;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longcai.cm.auth.token.LoginUserInfo;
import com.longcai.cm.auth.token.RequestUtil;
import com.longcai.cm.bean.Page;
import com.longcai.cm.bean.R;
import com.longcai.cm.common.utils.StringUtils;
import com.longcai.cm.domain.JaOrderComment;
import com.longcai.cm.domain.VGoodInfoList;
import com.longcai.cm.domain.vm.MemberVipViewModel;
import com.longcai.cm.moudules.system.bean.DicCode;
import com.longcai.cm.moudules.system.service.SysDicCodeService;
import com.longcai.cm.service.JaMemberVipService;
import com.longcai.cm.service.JaOrderCommentService;
import com.longcai.cm.service.VGoodInfoListService;
import com.longcai.cm.utils.GeoCalculator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * @author libingxing
 */
@RestController
@Api(tags = "商品相关接口")
@RequestMapping("/api/goods")
public class ApiGoodsController {

    @Resource
    private VGoodInfoListService goodInfoListService;

    @Resource
    private JaOrderCommentService orderCommentService;

    @Resource
    private SysDicCodeService sysDicCodeService;

    @Resource
    private JaMemberVipService memberVipService;

    @PostMapping("/goodsList")
    @ApiOperation("团购/秒杀 商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页", name = "page", dataType = "String", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "String", required = true),
            @ApiImplicitParam(value = "服务类型", name = "serviceInfo", dataType = "String", required = true),
            @ApiImplicitParam(value = "门店id", name = "shopId", dataType = "String", required = true),
            @ApiImplicitParam(value = "商品类型（1团购 2秒杀）", name = "type", dataType = "String", required = true),
            @ApiImplicitParam(value = "经度", name = "lng", dataType = "String", required = true),
            @ApiImplicitParam(value = "纬度", name = "lat", dataType = "String", required = true),
            @ApiImplicitParam(value = "城市", name = "city", dataType = "String", required = true),
            @ApiImplicitParam(value = "1距离 2好评 3销量 不传默认", name = "orderParam", dataType = "String", required = true),
    })
    public R<Page<List<VGoodInfoList>>> goodsList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows,
            String serviceInfo, String shopId,
            String lng, String lat, String type, String city,
            @RequestParam(defaultValue = "0") Integer orderParam
    ) {
        QueryWrapper<VGoodInfoList> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(serviceInfo)) {
            queryWrapper.eq("service_info", serviceInfo);
        }
        if (StringUtils.isNotBlank(type)) {
            queryWrapper.eq("type", type);
        }
        if (StringUtils.isNotBlank(shopId)) {
            queryWrapper.eq("shop_id", shopId);
        }
        if (StringUtils.isNotBlank(city)) {
            queryWrapper.eq("city", city);
        }
        queryWrapper.eq("status", 1);
        final long total = goodInfoListService.count(queryWrapper);
        queryWrapper.select("*, st_distance_sphere ( Point(" + lng + ", " + lat + "), location ) AS distance");
        final Page<List<VGoodInfoList>> result = new Page<>(page, rows, total);
        queryWrapper.last(result.convertPage());
        queryWrapper.orderByDesc("is_top");
        switch (orderParam) {
            case 1:
                queryWrapper.orderByAsc("distance");
                break;
            case 2:
                queryWrapper.orderByDesc("comment");
                break;
            case 3:
                queryWrapper.orderByDesc("sale_count");
                break;
            default:
                queryWrapper.orderByDesc("create_time");
                break;
        }
        final List<VGoodInfoList> list = goodInfoListService.list(queryWrapper);
        list.forEach(
                s -> {
                    if (StringUtils.isNotBlank(s.getExpireTime())) {
                        final DateTime expireTime = DateUtil.parse(s.getExpireTime());
                        s.setLeftTime((expireTime.getTime() - System.currentTimeMillis()) / 1000);
                    } else {
                        s.setLeftTime(0L);
                    }
                }
        );
        result.setContent(list);
        return R.success(result);
    }

    @PostMapping("/goodInfo")
    @ApiOperation("团购详情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "id", name = "id", dataType = "String", required = true),
            @ApiImplicitParam(value = "lat", name = "纬度", dataType = "String", required = true),
            @ApiImplicitParam(value = "lng", name = "经度", dataType = "String", required = true),
    })
    public R<VGoodInfoList> goodInfo(
            String id, double lat, double lng
    ) {
        final VGoodInfoList good = goodInfoListService.getById(id);
        if (good == null) {
            return R.error("商品走丢了");
        }
        final LambdaQueryWrapper<JaOrderComment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(JaOrderComment::getGoodId, good.getId());
        queryWrapper.orderByDesc(JaOrderComment::getCreateTime);
        good.setCommentCount(orderCommentService.count(queryWrapper));
        good.setCommentList(orderCommentService.list(queryWrapper));
        final String integralRatio = sysDicCodeService.getTextValueByCode(DicCode.INTEGRAL_RATIO);
        good.setIntegralRatio(new BigDecimal(integralRatio));
        final String integralRatioMax = sysDicCodeService.getTextValueByCode(DicCode.INTEGRAL_RATIO_MAX);
            good.setIntegralRatioMax(new BigDecimal(integralRatioMax));
        if (StringUtils.isNotBlank(good.getExpireTime())) {
            final DateTime expireTime = DateUtil.parse(good.getExpireTime());
            good.setLeftTime((expireTime.getTime() - System.currentTimeMillis()) / 1000);
        } else {
            good.setLeftTime(0L);
        }
        good.setDistance(GeoCalculator.calculateDistance(lat, lng, new BigDecimal(good.getLat()).doubleValue(), new BigDecimal(good.getLng()).doubleValue()));
        return R.success(good);
    }

    @PostMapping("/commentList")
    @ApiOperation("商品评价列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页", name = "page", dataType = "int", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "int", required = true),
            @ApiImplicitParam(value = "门店id", name = "shopId", dataType = "int", required = true),
            @ApiImplicitParam(value = "商品id", name = "goodId", dataType = "int", required = true),
    })
    public R<Page<List<JaOrderComment>>> commentList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows,
            String shopId, String goodId
    ) {
        final LambdaQueryWrapper<JaOrderComment> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(shopId)) {
            wrapper.eq(JaOrderComment::getShopId, shopId);
        }
        if (StringUtils.isNotBlank(goodId)) {
            wrapper.eq(JaOrderComment::getGoodId, goodId);
        }
        final long total = orderCommentService.count(wrapper);
        final Page<List<JaOrderComment>> result = new Page<>(page, rows, total);
        wrapper.last(result.convertPage());
        wrapper.orderByDesc(JaOrderComment::getCreateTime);
        final List<JaOrderComment> list = orderCommentService.list(wrapper);
        result.setContent(list);
        return R.success(result);
    }

}
